package com.example.johnerez.myapplication;

import android.accounts.AccountsException;
import android.app.ActionBar;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.AsyncTask;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.internal.widget.AdapterViewCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SearchView;
import android.widget.TextView;

import com.example.johnerez.myapplication.DataTypes.Dish;
import com.example.johnerez.myapplication.DataTypes.Restaurant;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class DishesViewActivity extends ActionBarActivity {
    private static final String DEBUG_TAG = "DEBUG_TAG";
    private DishTile dishTile;
    private DishAdapter adapter;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(DEBUG_TAG, "onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dishes_search);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new DishesViewFragment())
                    .commit();
        }
        handleIntent(getIntent());

    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.d(DEBUG_TAG, "onNewIntent() in DishesViewActivity");
        setIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        Log.d(DEBUG_TAG, "handleIntent()");
        this.dishTile = (DishTile) intent.getSerializableExtra("DishTile");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem searchViewItem = menu.findItem(R.id.search);
        android.support.v7.widget.SearchView searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(searchViewItem);
        searchView.setIconifiedByDefault(true);
        initializeSearchView(this, searchView);

        return true;
    }

    private static void initializeSearchView(final ActionBarActivity context, final android.support.v7.widget.SearchView searchView) {
        SearchManager searchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(
                new ComponentName(context.getApplicationContext(), DishesSearchActivity.class)));
        searchView.setSearchableInfo(searchManager.getSearchableInfo(context.getComponentName()));

        searchView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.d(DEBUG_TAG, "onQueryTextSubmit(" + query + ")");
                // Hide the keyboard and take focus off the search box.
                searchView.clearFocus();

                Intent intent = new Intent(context, DishesSearchActivity.class);
                intent.setAction(Intent.ACTION_SEARCH);
                intent.putExtra(SearchManager.QUERY, query);

                context.startActivity(intent);

                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Log.d(DEBUG_TAG, "onQueryTextChange(" + newText + ")");
                return false;
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public class DishesViewFragment extends Fragment {

        private DishAdapter adapter;
        private GoogleApiClient mGoogleApiClient;
        private Location mLastLocation;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            Log.d(DEBUG_TAG, "DishesViewFragment.onCreate()");
            super.onCreate(savedInstanceState);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            Log.d(DEBUG_TAG, "onCreateView()");
            View rootView = inflater.inflate(R.layout.fragment_dishes_view, container, false);

            //adapter = new DishAdapter(getActivity());
            //restaurantView.setAdapter(adapter);

            DishTile tileData = ((DishesViewActivity) getActivity()).dishTile;

            TextView restaurantNameView = (TextView) rootView.findViewById(R.id.restaurantName);
            RatingBar ratingBar = (RatingBar) rootView.findViewById(R.id.dishStarRating);
            TextView priceView = (TextView) rootView.findViewById(R.id.dishPrice);
            //TextView dishDescriptionView = (TextView) view.findViewById(R.id.dishDescription);

            restaurantNameView.setText(tileData.restaurant.name);
            ratingBar.setRating(tileData.restaurant.yelpRating);
            //dishDescriptionView.setText(tileData.dish.description);

            listView = (ListView) rootView.findViewById(R.id.listView);
            adapter = new DishAdapter(getActivity());
            listView.setAdapter(adapter);


            List<DishTile> dishes = new ArrayList<>();
            for (Dish dish : dishTile.restaurant.matchingDishes) {
                dishes.add(new DishTile(dish, dishTile.restaurant));
                Log.d(DEBUG_TAG, dish.name);

            }
            adapter.setDishes(dishes);

/*
            listView = (ListView) rootView.findViewById(R.id.listView);
            adapter = new DishAdapter(getActivity());
            listView.setAdapter(adapter);

            progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
            progressBar.setVisibility(View.GONE);

            SearchView searchView = (SearchView) rootView.findViewById(R.id.searchView);
            initializeSearchView((ActionBarActivity) getActivity(), searchView);


            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                                        long id) {
                    Log.d(DEBUG_TAG, "got item click");
                    Intent intent = new Intent(view.getContext(), DishesViewActivity.class);
                    view.getContext().startActivity(intent);
                    //String message = "abc";
                    //intent.putExtra(EXTRA_MESSAGE, message);
                    //startActivity(intent);
                }
            });
            */
            return rootView;
        }
    }
}
